package com.itbuka.oauth.controller;

import com.itbuka.entity.Result;
import com.itbuka.oauth.service.AuthService;
import com.itbuka.utils.CookieUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.util.Map;

/**
 * 用户认证
 */
@RestController
@RequestMapping("/auth")
public class AuthController {

    @Autowired
    private AuthService authService;
    //客户端id
    @Value("${auth.clientId}")
    private String clientId;
    //客户端密钥
    @Value("${auth.clientSecret}")
    private String clientSecret;
    //token过期时间
    @Value("${auth.ttl}")
    private Integer ttl;
    //cookie域名
    @Value("${auth.cookieDomain}")
    private String cookieDomain;
    //cookie路径
    @Value("${auth.cookiePath}")
    private String cookiePath;
    //cookie存活时间
    @Value("${auth.cookieMaxAge}")
    private Integer cookieMaxAge;

    /**
     * 登录
     */
    @RequestMapping("/login")
    public Result login(@RequestParam String username, @RequestParam String password, HttpServletResponse response) {
        Map<String, String> login = authService.login(username, password, clientId, clientSecret, ttl);
        // 添加cookie中
        CookieUtil.addCookie(response, cookieDomain, cookiePath, "token", login.get("jti"), cookieMaxAge, false);
        return Result.ok("登录成功", login);
    }
}